package com.fh.web.controller;

import com.fh.common.api.vo.Result;
import com.fh.common.constant.ActionLogResult;
import com.fh.common.constant.CommonConstant;
import com.fh.common.web.AbstractController;

import com.fh.modules.ucas.entity.SysUser;
import com.fh.modules.ucas.model.SysLoginModel;
import com.fh.shiro.RedisService;
import com.fh.shiro.ShiroUtils;
import com.fh.shiro.vo.DefContants;
import com.fh.web.service.ISysLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Qiu,Junda
 * @date 2019年4月3日
 * @description 登录
 */
@RestController
@RequestMapping("/sys")
@Api("用户登录")
public class LoginController extends AbstractController{
	@Autowired
	private ISysLoginService loginService;

	@Autowired
    private RedisService redisService;
	

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ApiOperation("登录接口")
	public Result login(@RequestBody SysLoginModel sysLoginModel) {
		return loginService.login(sysLoginModel);
	}
	
	/**
	 * 退出登录
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public Result<Object> logout(HttpServletRequest request,HttpServletResponse response) {
		//用户退出逻辑
		Subject subject = ShiroUtils.getShiroSubject();
		SysUser sysUser = (SysUser)subject.getPrincipal();
//		sysBaseAPI.addLog("用户名: "+sysUser.getRealname()+",退出成功！", CommonConstant.LOG_TYPE_LOGIN,3,ActionLogResult.SUCCESS,"success");
	    subject.logout();
	    String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
//	    //清空用户Token缓存
	    redisService.del(CommonConstant.PREFIX_USER_TOKEN + token);
	    //清空用户权限缓存：权限Perms和角色集合
	    redisService.del(CommonConstant.LOGIN_USER_CACHERULES_ROLE + sysUser.getUsername());
	    redisService.del(CommonConstant.LOGIN_USER_CACHERULES_PERMISSION + sysUser.getUsername());
		return Result.ok("退出登录成功！");
	}
	
	/**
	 * 验证token
	 * @return
	 */
	@GetMapping("/validateToken")
	@ApiOperation("验证token")
	public Result validateToken() {
		return Result.ok("success");
	}

}
